package 线程池;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lenovo
 * Date: 2022-10-05
 * Time: 10:08
 */
class MytTPool{
    //阻塞队列,生产者-消费者模型 来处理线程池里m个线程和n个任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingDeque();
    public void submit(Runnable runnable) throws InterruptedException {//submit接收任务
        //将任务放入到队列里
        queue.put(runnable);
    }
    //创建线程池并且
    public MytTPool(int m) {
        for (int i = 0; i < m; i++) {
            Thread t =new Thread(){
                @Override
                public void run() {
                    while (true){//每个线程里都有一个while循环,可以持续扫描这个阻塞队列
                        try {
                            queue.take().run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            t.start();

        }
    }
}
public class demo5 {
    public static void main(String[] args) throws InterruptedException {
        MytTPool pool = new MytTPool(10);
        for (int i = 0; i < 100; i++) {
            int id = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("这是我的任务:"+id+"  "+"线程名:"+Thread.currentThread().getName());
                }
            });
        }

    }
}
